// pages/home/home.js
const storageManager = require('../../utils/storage.js');

Page({
    data: {
        // 统计数据
        totalCharts: 0,
        recentlyViewed: 0,
        favoriteCharts: 0,

        // 图表列表
        chartList: [],

        // 过滤器
        currentFilter: 'all',

        // 最近活动
        recentActivity: []
    },

    onLoad() {
        console.log('Home page loaded');
        this.loadChartData();
    },

    onShow() {
        console.log('Home page show');
        // 每次显示页面时重新加载数据，以确保显示最新的图表
        this.loadChartData();
    },

    /**
     * 加载图表数据
     */
    loadChartData() {
        const chartList = storageManager.getChartList();
        console.log('Loading chart data:', chartList);
        
        this.setData({
            chartList: chartList,
            totalCharts: chartList.length,
            recentlyViewed: Math.min(chartList.length * 2, 20), // 模拟最近查看数
            favoriteCharts: Math.floor(chartList.length / 2) // 模拟收藏数
        });
        
        this.generateRecentActivity(chartList);
    },

    /**
     * 生成最近活动数据 - 暂时禁用
     */
    generateRecentActivity(chartList) {
        // 暂时禁用最近活动功能
        this.setData({
            recentActivity: []
        });
    },

    /**
     * 格式化时间为"几分钟前"的形式
     */
    formatTimeAgo(dateString) {
        const now = new Date();
        const date = new Date(dateString);
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / (1000 * 60));
        const diffHours = Math.floor(diffMins / 60);
        const diffDays = Math.floor(diffHours / 24);
        
        if (diffMins < 1) return '刚刚';
        if (diffMins < 60) return `${diffMins}分钟前`;
        if (diffHours < 24) return `${diffHours}小时前`;
        if (diffDays < 7) return `${diffDays}天前`;
        return date.toLocaleDateString();
    },

    /**
     * 过滤器切换
     */
    onFilterChange(e) {
        const filter = e.currentTarget.dataset.filter;
        this.setData({
            currentFilter: filter
        });
        // TODO: 实现过滤逻辑
    },

    /**
     * 查看图表详情（预览页面）
     */
    onViewChart(e) {
        const chart = e.currentTarget.dataset.chart;
        if (chart && chart.id) {
            wx.navigateTo({
                url: `/pages/chart-preview/chart-preview?id=${chart.id}`
            });
        }
    },

    /**
     * 编辑图表
     */
    editChart(e) {
        const chart = e.currentTarget.dataset.chart;
        if (chart && chart.id) {
            wx.navigateTo({
                url: `/pages/addCharts/addCharts?id=${chart.id}`
            });
        }
    },

    /**
     * 删除图表
     */
    deleteChart(e) {
        const chart = e.currentTarget.dataset.chart;
        if (!chart || !chart.id) return;
        
        wx.showModal({
            title: '确认删除',
            content: `确定要删除图表"${chart.title}"吗？此操作不可撤销。`,
            confirmText: '删除',
            confirmColor: '#ff0096',
            success: (res) => {
                if (res.confirm) {
                    this.performDeleteChart(chart);
                }
            }
        });
    },

    /**
     * 执行删除图表操作
     */
    performDeleteChart(chart) {
        // 从图表列表中删除
        const chartList = storageManager.getChartList();
        const filteredList = chartList.filter(item => item.id !== chart.id);
        const success = storageManager.saveChartList(filteredList);
        
        if (success) {
            // 删除图表数据
            storageManager.deleteChartData(chart.id);
            // 删除可能存在的草稿
            storageManager.deleteDraft(chart.id);
            
            wx.showToast({
                title: '删除成功',
                icon: 'success'
            });
            
            // 重新加载数据
            this.loadChartData();
        } else {
            wx.showToast({
                title: '删除失败',
                icon: 'error'
            });
        }
    },

    /**
     * 创建新图表
     */
    createNewChart() {
        wx.navigateTo({
            url: '/pages/addCharts/addCharts'
        });
    },

    // 跳转到图表页面
    goToCharts() {
        wx.switchTab({
            url: '/pages/charts/charts'
        });
    },

    // 跳转到个人页面
    goToProfile() {
        wx.switchTab({
            url: '/pages/profile/profile'
        });
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: 'ChartLite - 轻松创建精美图表',
            path: '/pages/home/home',
            imageUrl: '/images/share-cover.png'
        };
    }
})